package com.leyou.item.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.exception.BusinessException;
import com.leyou.exception.pojo.BusinessExceptionEnum;
import com.leyou.item.mapper.IBrandMapper;
import com.leyou.item.mapper.ICategoryBrandMapper;
import com.leyou.item.pojo.Brand;
import com.leyou.item.pojo.CategoryBrand;
import com.leyou.item.service.IBrandService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * 商品业务逻辑实现层
 */
@Service
public class BrandServiceImpl implements IBrandService {

    @Autowired
    private IBrandMapper brandMapper;

    @Autowired
    private ICategoryBrandMapper categoryBrandMapper;

    /**
     * 查询品牌列表信息
     *
     * @param key    搜索条件
     * @param page   当前页
     * @param rows   每显示的条数
     * @param sortBy 排序字段
     * @param desc   是否降序
     * @return
     */
    @Override
    public PageResult<Brand> findBrandByPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) throws Exception{
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();
        // 设置查询条件
        if(StringUtils.isNotBlank(key)){
            criteria.andLike("name","%"+key+"%")
                    .orEqualTo("letter",key);
        }
        // 设置分页条件
        PageHelper.startPage(page,rows);
        // 添加排序条件
        if(StringUtils.isNotBlank(sortBy)){
            example.setOrderByClause(sortBy+" "+(desc ? "desc" : "asc"));
        }
        // 查询列表
        List<Brand> brands = this.brandMapper.selectByExample(example);
        // 包装成pageInfo
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);
        PageResult<Brand> pageResult = new PageResult<>();
        pageResult.setItems(pageInfo.getList());
        pageResult.setTotal(pageInfo.getTotal());
        pageResult.setTotalPage(pageInfo.getPages());
        return pageResult;
    }

    /**
     * 添加商品和商品分类关联信息
     *
     * @param brand
     * @param cids
     */
    @Override
    @Transactional
    public void saveBrandAndCategoryBrand(Brand brand, List<Long> cids) throws Exception{

        // 添加商品
        int row = brandMapper.insertSelective(brand);

        if(row == 1){
            cids.forEach(cid -> {
                CategoryBrand categoryBrand = new CategoryBrand();
                categoryBrand.setCategoryId(cid);
                categoryBrand.setBrandId(brand.getId());
                this.categoryBrandMapper.insert(categoryBrand);
            });
        }
    }
}
